package com.hl.util;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JdbcUtil {

    public static Connection connection;
    public static DataSource  dataSource;
    static{
//        创建数据库连接池
//        自动读取c3p0-config.xml文件，找到默认的数据库连接配置，创建数据源,获取连接池
         dataSource = new ComboPooledDataSource("mysql");
    }
    public static Connection open(){
        //2、创建连接
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return connection;
    }

    public static void close(ResultSet rs, Statement statement,Connection connection){
//        3.关闭连接
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(statement != null){
            try {
                statement.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        if(connection != null){
            try {
//                如果是new的连接，销毁，如果是从连接池中的连接，自动归还到连接池中
                connection.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }


}

